package com.metagurukul.informer.servlets;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.metagurukul.informer.service.AnswerService;

/**
 * Servlet implementation class InsertAnswer
 */
@WebServlet("/InsertAnswer")
public class InsertAnswer extends HttpServlet {
	private static final long serialVersionUID = 1L;
     

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.sendRedirect("ShowQuestions");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session=request.getSession();
		try {
			if(session.getAttribute("userName")==null && session.getAttribute("adminName")==null){
				  response.sendRedirect("login.jsp");
			  }else{
				  String question_id=request.getParameter("question_id");
					String answer=request.getParameter("answer");
					if(answer==null || answer.trim().equals("")){
						response.sendRedirect("ShowQuestion?id="+question_id);
					}
					else{
						answer=answer.trim();
						AnswerService answerService=new AnswerService();
						String user=null;
						if(session.getAttribute("userName")!=null){
							user=(String)session.getAttribute("userName");
						}
						else{
							user=(String)session.getAttribute("adminName");
						}
						int question_id_int=Integer.parseInt(question_id);
						answerService.insertAnswer(question_id_int,answer,user);
						response.sendRedirect("ShowQuestion?id="+question_id);
					}
			  }
		} catch (SQLException e) {
			response.sendRedirect("Error.jsp");
		}
	}

}
